package com.doradance.app;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import com.doradance.R;
import com.doradance.account.Account;
import com.doradance.account.AccountManager;
import com.doradance.account.ParamKey;
import com.doradance.account.UrlCenter;
import com.doradance.account.ui.LoginActivity;
import com.doradance.app.storagemanager.SpDao;
import com.doradance.common.http.MyHttpRequest;
import com.doradance.common.http.TokenInfo;
import com.pachong.android.baseuicomponent.CompState;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.frameworkbase.dialog.ProgressFragment;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.pachong.android.frameworkbase.utils.MD5Util;
import com.pachong.android.frameworkbase.utils.SLog;


import org.json.JSONException;
import org.json.JSONObject;

public class SplashActivity extends BaseActivity {

    Handler handler = new Handler();
    private boolean mIsFirstStart;
     Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        hideToolbar();
        //定义全屏参数
        int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN;
        //获得窗口对象
        Window mywindow = this.getWindow();
        //设置Flag标识
        mywindow.setFlags(flag,flag);
//        //设置状态栏黑色
//        if (Build.VERSION.SDK_INT >= 21) {
//            getWindow().setStatusBarColor(Color.BLACK);
//        }
        mIsFirstStart = SpDao.isFirstTimeStartApp(this);
    initActivity();
}

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.act_splash, null);
    }

    private void initActivity() {

        intent = new Intent();
        handler.postDelayed(new Runnable() {
            public void run() {
                if (mIsFirstStart) {
                    intent.setClass(SplashActivity.this, GuideActivity.class);
                    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                    startActivity(intent);
                    finish();
                    SpDao.setKeyFirstTimeStartApp(SplashActivity.this, false);
                } else {
//                    if(auautoLogin()){
//                        autoLogin();
//                    }else{
                        intent.setClass(SplashActivity.this, LoginActivity.class);
                        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                        startActivity(intent);
                        finish();
//                    }
                }
            }
        }, 1500);
    }
    private void autoLogin() {
        String checksum = MD5Util.getMd5(MD5Util.getMd5("haimi"+ AccountManager.getCurrentAccount().getMacKey()  +AccountManager.getCurrentAccount().getPhone() )) + getTime();
        MyHttpRequest request = new MyHttpRequest(this);
        JSONObject jobj = new JSONObject();
        try {
            jobj.put(ParamKey.CURRENT_TIME,getTime());
            jobj.put(ParamKey.LOGIN_NAME,AccountManager.getCurrentAccount().getPhone());
            jobj.put(ParamKey.CHECK_SUM,checksum);
            request.post(UrlCenter.AUTOLOGIN, jobj, new DataRequestListener<TokenInfo>(TokenInfo.class) {
                @Override
                public void onStart(Context context, String url) {
                    super.onStart(context, url);
                }
//                @Override
//                public void enableProgress(boolean enableProgress) {
//                    super.enableProgress(enableProgress);
//                    if(enableProgress){
//                        enableProgress(false);
//                    }
//                }
                @Override
                public void onSuccess(TokenInfo tokenInfo) {
                    super.onSuccess(tokenInfo);
                    if(tokenInfo!=null){
                        Log.e("tokenInfo1",tokenInfo.toString());
                        AccountManager.updateTokenInfo(tokenInfo);
                        setAccount(tokenInfo.getUser_id(),tokenInfo.getMacKey());
                        intent.setClass(SplashActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    }else{
                        EasyToast.showToast(SplashActivity.this,"请重新登录");
                        LoginActivity.start(SplashActivity.this);
                    }
                }
                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                    EasyToast.showToast(SplashActivity.this,strMsg);
                    LoginActivity.start(SplashActivity.this);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //获得当前系统时间的时间戳
    public String getTime(){
        long time=System.currentTimeMillis()/1000;//获取系统时间的10位的时间戳
        String  str=String.valueOf(time);
        return str;
    }

    //自动登录
    private boolean  auautoLogin() {
        if (AccountManager.getCurrentAccount() == null) {//未登录
            SLog.e("nullnullnl");
            return false;
        } else {//自动登录
           return true;
        }
    }

    /**
     * 获取用户信息
     *
     * @param userId
     */
    private void setAccount(String userId, final String macKey) {
        Log.e("userId",userId);
        Log.e("macKey",macKey);
        IHttpRequest request = new MyHttpRequest(this);
        String requestUrl = String.format(UrlCenter.USER, new Object[]{userId});
        request.get(requestUrl, null, new DataRequestListener<Account>(Account.class) {


            @Override
            public void onSuccess(Account account) {
                account.setPassWord(account.getPassWord());
                account.setPhone(account.getPhone());
                account.setMacKey(macKey);
                AccountManager.setCurrentAccount(account);
                EasyToast.showToast(SplashActivity.this, "登录成功");
                MainActivity.start(SplashActivity.this);
                finish();
            }

            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                EasyToast.showToast(SplashActivity.this,strMsg);
            }
        });
    }
}
